<template>
    <a-spin :spinning="loading">
        <div
                v-if="!dataSource || !dataSource.length"
                class="t-table-body--empty"
        >
            <a-empty/>
        </div>
        <a-tree style="minx-height: 200px;max-height: 400px;width: 100%; overflow: auto"
                v-else
                :class="{'disabledTree': disabled}"
                :expandedKeys="expandedKeys"
                v-model:selectedKeys="selectedKeys.checked"
                @expand="expandNode"
                checkable
                @check="checkNode"
                :tree-data="dataSource"
                :replace-fields="{
                    children:'children', title:'name', key:'id'
                  }"
        />
    </a-spin>
</template>

<script>
  import { getAuthResource } from '@/api/system/system.js'
  import { clientId } from '@/config'
  import { Empty } from 'ant-design-vue'
  // import mockData from './test.js'

  export default {
    name: 'RoleTree',
    props: {
      rowKey: {
        type: String,
        default: 'id'
      },
      disabled: {
        type: Boolean,
        default: false
      },
      selectedRowKeys: {
        type: Array,
        default() {
          return []
        }
      },
      // 是否初始化选中
      selectedInitial: {
        type: Boolean,
        default: true
      },
      userId: {
        type: String,
        default: ''
      },
      roleId: {
        type: String,
        default: ''
      },
      tabType: {
        type: String,
        default: '1'
      },
      isCopy: {
        type: Boolean,
        default: false
      }
    },
    components: {
      AEmpty: Empty
    },
    watch: {
      selectedRowKeys: {
        handler(val) {
          if (!this.selectedInitial) {
            this.selectHalfAndCheckKeys = val
            this.selectedKeys.checked = []
            this.getAuthResourceReq()
          }
        }
      }
    },
    data() {
      return {
        // autoExpandParent: false,
        dataSource: [],
        expandedKeys: [],
        selectedKeys: {
          checked: []
        },
        loading: false,
        isAdd: false,
        selectHalfAndCheckKeys: [], //半选及全选节点的key
        autoKeys: []
      }
    },
    mounted() {
      if (this.$route.query.pageType) {
        if (this.$route.query.pageType == 'add') {
          this.isAdd = true
        } else {
          this.isAdd = false
        }
      }
      this.getAuthResourceReq()
    },
    methods: {
      setSelectKeys(arr, checked) {
        let keys = []
        arr.forEach(item => {
          keys.push(item.id)
          if (item.children && item.children.length) {
            keys = keys.concat(this.setSelectKeys(item.children, checked))
          }
        })
        return keys
      },
      getParentKeys(node) {
        let keys = []
        if(node.$parent.dataRef) {
          keys.push(node.$parent.dataRef.id)
          if(node.$parent) {
            keys = keys.concat(this.getParentKeys(node.$parent))
          }
        }
        return keys
      },
      checkNode(checkedKeys, e) {
        this.selectHalfAndCheckKeys = [...this.selectedKeys.checked, ...e.halfCheckedKeys]
        console.log(this.selectHalfAndCheckKeys, 'this.selectHalfAndCheckKeys')
      },
      getLastNodeKeys(list) {
        list.forEach(item=>{
          if(!item.children || !item.children.length) {
            // 找到最后一级了
            if( this.autoKeys.includes(item.id)) {
              this.selectedKeys.checked.push(item.id)
            }
          } else {
            this.getLastNodeKeys(item.children)
          }
        })
      },
      getChildrenKeys(node) {
        let arr = []
        arr.push(node.id)
        if(node.children) {
          node.children.forEach(item=>{
            arr = arr.concat(this.getChildrenKeys(item))
          })
        }
        return arr
      },
      expandNode(expandedKeys, {expanded, node}) {
        const expandNodeKeys = this.getChildrenKeys(node.dataRef)
        if(expanded) {
          // 加
          const arr = []
          expandNodeKeys.forEach(item=>{
            if(!this.expandedKeys.includes(item)) {
              arr.push(item)
            }
          })
          this.expandedKeys.push(...arr)
        } else {
          // 删
          const arr2 = []
          this.expandedKeys.forEach(item=>{
            if(!expandNodeKeys.includes(item)) {
              arr2.push(item)
            }
          })
            this.expandedKeys = arr2;
        }
      },
      async getAuthResourceReq() {
        if (this.loading) return
        this.loading = true
        const params = {
          userId: this.userId || void 0, // 用户ID
          role: this.roleId || void 0, // 角色ID
          clientId: clientId,
          resTypes: this.tabType === '1' ? '1,2,9' : '1,9' // 1：菜单  2：按钮  9：url
        }
        try {
          const res = await getAuthResource(params)
          let resultList = res.data
          //todo 模拟
          // let resultList = JSON.parse(JSON.stringify(mockData))
          const idx = resultList.findIndex(item => item.data.resource.title === '项目管理')
          const idx2 = resultList[idx].children.findIndex(item => item.data.resource.title === '业务查询')
          if (this.tabType === '1') {
            resultList[idx].children.splice(idx2, 1)
          } else {
            const r = resultList[idx].children[idx2]
            resultList = [r]
          }
          this.autoKeys = []
          // 遍历树，构建需要的数据结构
          const depFn = (list, deepth = 1) => {
            list &&
            list.forEach((item) => {
              item.name = item.data.resource.title
              if (this.isAdd && this.tabType === '2'&&!this.isCopy) {
                this.selectedKeys.checked.push(item.id)
                this.selectHalfAndCheckKeys.push(item.id)
              } else {
                // selectedInitial为false时，则根据selectedKeys进行初始化选中
                if (!this.selectedInitial) {
                  if (this.selectedRowKeys.includes(item[this.rowKey])) {
                    this.autoKeys.push(item.id)
                  }
                } else {
                  if (item.data.resource.authorized) {
                    this.autoKeys.push(item.id)
                  }
                }
              }
              // item.indeterminate = false
              // item.showContent = false
              item.deepth = deepth
              // item.disabled = !!this.disabled
              if (item.children) {
                depFn(item.children, deepth + 1)
              }
            })
          }
          depFn(resultList)
          this.dataSource = resultList
          // 回显
          this.getLastNodeKeys( this.dataSource)
          this.$emit('loadFinish', this.tabType)
        } catch (e) {
          console.error(e)
        } finally {
          this.loading = false
        }
      },
      getSelectedList() {
        const selectedList = []
        const deepFn = (list) => {
          list &&
          list.forEach((item) => {
            // 筛选出选中状态,及半选状态的节点
            if (this.selectHalfAndCheckKeys.includes(item.id)) {
              selectedList.push(item)
            }
            item.children && deepFn(item.children)
          })
        }
        deepFn(this.dataSource)
        return selectedList
      }
    }
  }
</script>

<style scoped lang="less">
    @borer-color: #e8e8e8;
    .t-table-body--empty {
        height: 400px;
        border-right: 1px solid @borer-color;
        border-bottom: 1px solid @borer-color;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .disabledTree /deep/ .ant-tree-checkbox-inner {
        background-color: #f5f5f5!important;
        border-color: #d9d9d9 !important;
        cursor: not-allowed;
    }
    .disabledTree /deep/ .ant-tree-checkbox-checked .ant-tree-checkbox-inner::after {
        border-color: rgba(0, 0, 0, 0.25) !important;
    }
    .disabledTree /deep/ .ant-tree-checkbox-checked:hover {
        border-color: rgba(0, 0, 0, 0.25) !important;
    }
    .disabledTree /deep/.ant-tree-node-content-wrapper span, .disabledTree /deep/ .ant-tree-node-content-wrapper {
        color:  rgba(0, 0, 0, 0.25) !important;
        cursor: not-allowed;
    }
    .disabledTree  /deep/ .ant-tree-node-content-wrapper:hover {
        background-color: transparent;
    }
    .disabledTree /deep/ .ant-tree-checkbox-indeterminate .ant-tree-checkbox-inner:after {
        background-color: rgba(0, 0, 0, 0.25) !important;
    }
    .disabledTree /deep/ .ant-tree-checkbox{
        cursor: not-allowed!important;
        pointer-events: none!important;
    }
    /deep/ .ant-tree li {
        /*display: flex;*/
        padding: 0;
        margin-bottom: 5px;
        display: block;
        min-width: 100%;
    }
    /deep/ .ant-tree li ul {
        display: inline-block!important;
        min-width: 260px;
    }
    /deep/ .ant-tree .ant-tree-checkbox {
        vertical-align: top;

    }
</style>
